<?php
namespace App\Admin\Controllers;

use App\Models\AdminApiMenusModel;
use App\Models\AdminMenusModel;
use App\Models\AdminRolesModel;
use App\Services\SessionService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Lib\Util\JWT;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected $check_login = true;

    protected $request;

    protected $admin_info;

    public function __construct(Request $request)
    {
        $this->request = $request;

        $client_token = $request->header('X-Token') ?? '';
        $admin_info = SessionService::getInstance()->get(md5($client_token));

        if ($this->check_login && !$admin_info) {
            $this->fail(CODE_ERR_AUTH, '未登陆，请先登录！');
            exit;
        }
        $payload = JWT::verifyToken($client_token);

        $this->admin_info = $payload['admin_info'];

        if ($this->check_login && !$this->admin_info['is_admin']) {
            $is_permiss = false;
            $action = Request()->route()->getActionName();
            list($controller, $action) = explode('@', $action);

            $menu_ids = AdminRolesModel::query()->where('id', $this->admin_info['role_id'])->first(['menu_ids'])->toArray();
            $menu_id_arrs = explode(',', $menu_ids['menu_ids']);
            $api_menus = AdminMenusModel::query()->whereIn('id', $menu_id_arrs)->get()->toArray();
            $api_menu_ids = [];
            foreach ($api_menus as $api_menu) {
                $api_menu_ids = array_values(array_unique(array_filter(array_merge($api_menu_ids, explode(',', $api_menu['api_menu_ids'])))));
            }

            $admin_apis = AdminApiMenusModel::query()->whereIn('id', $api_menu_ids)->orWhere('is_check', NO)->get()->toArray();
            foreach ($admin_apis as $api){
                if ($api['controller'] === $controller && $api['action'] === $action) {
                    $is_permiss = true;
                    break;
                }
            }

            if (!$is_permiss) {
                $this->fail(CODE_ERR_DENY, '接口未授权，请联系管理员开通');
                exit;
            }
        }
    }


    /**
     * 返回成功的请求
     * @param array $data
     * @param string $message
     * @return bool
     */
    public function success(array $data = [], $message = '操作成功')
    {
        $response = [
            'code' => CODE_SUCCESS,
            'message' => $message,
            'data' => $data ?: [],
        ];

        $action = Request()->route()->getActionName();
        list($controller, $action) = explode('@', $action);

        Log::info(json_encode([
            'response' => $response,
            'request' => Request()->all(),
            'route' => Request()->route(),
            'controller' => $controller,
            'action' => $action,
        ], JSON_UNESCAPED_UNICODE));

        echo json_encode($response, JSON_UNESCAPED_UNICODE);

        return false;
    }

    /**
     * @param int $code
     * @param string|null $message
     * @return bool
     */
    public function fail(int $code = -1, ?string $message = '')
    {
        $response = [
            'code' => $code,
            'message' => $message ?: $GLOBALS['CODE_MESSAGES'][$code] ?? '操作失败',
            'payload' => [],
        ];

        Log::error(json_encode([
            'response' => $response,
            'request' => Request()->all(),
            'route' => Request()->route()
        ], JSON_UNESCAPED_UNICODE));

        echo json_encode($response, JSON_UNESCAPED_UNICODE);

        return false;
    }

}
